<html>
<head>
  <meta content="text/plain" charset="utf-8" />
  <script src="script/pouchdb-5.3.1.min.js"></script>
  <script src="script/jquery-2.1.4.min.js"></script>
</head>
<body onload="showTodos()">
<script>
var db = new PouchDB('todos');
var remoteCouch = false;

db.changes({
  since: 'now',
  live: true
}).on('change', showTodos);

function addTodo(text) {
  var todo = {
    _id: new Date().toISOString(),
    title: text,
    completed: false
  };
  db.put(todo, function callback(err, result) {
    if (!err) {
      console.log('Successfully posted a todo!');
    }
  });
}

function showTodos() {
  db.allDocs({include_docs: true, descending: true}, function(err, doc) {
    console.log(doc.total_rows);
    redrawTodosUI(doc.rows);
  });
}

function redrawTodosUI(rows) {
  var ul = $('#todoList_ul');
  ul.empty();
  for (row of rows) {
    ul.append("<li>" + row.doc._id + "----" + row.doc.title + "</li>");
  }
}

function checkboxChanged(todo, event) {
  todo.completed = event.target.checked;
  db.put(todo);
}

function deleteButtonPressed(todo) {
  db.remove(todo);
}

function todoBlurred(todo, event) {
  var trimmedText = event.target.value.trim();
  if (!trimmedText) {
    db.remove(todo);
  } else {
    todo.title = trimmedText;
    db.put(todo);
  }
}

function searchTodo(text) {
  db.get('_design/title_index').then(function(doc) {
    db.remove(doc);
  })

  var ddoc = {
    _id:"_design/title_index",
    view : {
      by_title : {
        map : function mapF(doc) {
          if (doc.title) {
            emit(doc.title);
          }
        }.toString()
      }
    }
  }

  db.put(ddoc).catch(function (err){
    if (err.status != 409) {
      throw err;
    }
  })

  db.query('title_index/by_title', {
    key:text,
    include_docs: true
  }).then(function(result){
    alert(result.doc.title);
  }).catch(function(err) {
    console.log(err);
  })
}
</script>

<div id="add_div">
  <input type="text" id="add_title" name="title" value="">
  <input type="button" name="add_but" value="加入TODO" onclick="script:addTodo($('#add_title').val())">
</div>

<div id="search_div">
  <input type="text" id="search_title" value="">
  <input type="button" name="search_but" value="查询TODO" onclick="script:searchTodo($('#search_title').val())">
</div>

<div id="todoList_div">
  <ul id="todoList_ul"></ul>
</div>
</body>
</html>
